package com.xiaozhou.controller;

import com.xiaozhou.function.FunctionManager;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.service.v4.api.AssistantClientService;
import com.zhipu.oapi.service.v4.assistant.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shhzhou
 * @description: 智能体会话 范例
 * @date 2024/11/4 16:03
 */
@RestController
@RequestMapping("/assistant")
public class AssistantController {

    @Autowired
    private ClientV4 clientV4;

    @Autowired
    private FunctionManager functionManager;

    /**
     * @Author xiaozhou
     * @Description  智能体会话
     * @Date 16:27 2024/11/4
     * @Param
     * @return
     * @return reactor.core.publisher.Flux<com.zhipu.oapi.service.v4.assistant.AssistantCompletion>
     */
    @RequestMapping("/sseModel")
    public Flux<AssistantCompletion> sseModel() {

        List<ConversationMessage> messages = new ArrayList<>();
        List<MessageTextContent> content = new ArrayList<>();

        MessageTextContent messageTextContent = new MessageTextContent();
        messageTextContent.setType("text");
        messageTextContent.setText("北京未来七天气温，做个折线图");

        content.add(messageTextContent);
        messages.add(new ConversationMessage("user", content));

        // 构造模型参数
        AssistantParameters assistantParameters = new AssistantParameters();
        assistantParameters.setAssistantId("65a265419d72d299a9230616");
        assistantParameters.setModel("glm-4-assistant");
        assistantParameters.setStream(true);
        assistantParameters.setMessages(messages);

        AssistantApiResponse apply = new AssistantClientService(clientV4.getConfig().getHttpClient(), clientV4.getConfig().getBaseUrl())
                .assistantCompletionStream(assistantParameters).apply(clientV4);

        // 使用 Flux.create 创建流
        return Flux.create(sink -> {
            apply.getFlowable().map(modelData -> {
                return modelData;
            }).doOnNext(modelData -> {
                sink.next(modelData);
            }).doOnComplete(() -> {
                sink.complete();
            }).blockingSubscribe();
        });
    }






}
